from odoo import api, fields, models


class AgriDatasetEntry(models.Model):
    _name = 'agri.dataset.entry'
    _description = '训练数据条目'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'create_date desc'

    name = fields.Char(string='编号', required=True, copy=False, default='新建')
    detection_id = fields.Many2one('agri.detection.session', string='来源识别记录', ondelete='set null')
    contributor_id = fields.Many2one('res.partner', string='贡献人', tracking=True)
    capture_time = fields.Datetime(string='拍摄时间', default=lambda self: fields.Datetime.now())
    image_1920 = fields.Image(string='样本图片', max_width=1920, max_height=1920, required=True)
    label_type = fields.Selection(
        selection=[
            ('disease', '病叶'),
            ('pest', '虫害'),
            ('healthy', '健康'),
            ('other', '其他'),
        ],
        string='标签类型',
        default='disease',
        tracking=True,
    )
    disease_id = fields.Many2one('agri.disease', string='病害标签', tracking=True)
    pest_id = fields.Many2one('agri.pest', string='虫害标签', tracking=True)
    custom_label = fields.Char(string='自定义标签')
    status = fields.Selection(
        selection=[
            ('draft', '待标注'),
            ('labeled', '已标注'),
            ('approved', '已审核'),
            ('rejected', '已驳回'),
        ],
        default='draft',
        string='标注状态',
        tracking=True,
    )
    split = fields.Selection(
        selection=[
            ('train', '训练集'),
            ('val', '验证集'),
            ('test', '测试集'),
        ],
        default='train',
        string='数据集分配',
        tracking=True,
    )
    device_id = fields.Char(string='采集设备ID')
    model_version = fields.Char(string='模型版本')
    extra_meta = fields.Json(string='额外元数据')
    notes = fields.Text(string='备注')
    crop_id = fields.Many2one('agri.crop', string='作物')
    annotation_format = fields.Selection(
        selection=[
            ('yolo', 'YOLO TXT'),
            ('coco', 'COCO JSON'),
            ('pascal', 'Pascal VOC'),
            ('custom', '自定义'),
        ],
        default='yolo',
        string='标注格式',
    )
    annotation_payload = fields.Json(string='标注内容')
    exported_at = fields.Datetime(string='导出时间')
    export_batch = fields.Char(string='导出批次')
    exported = fields.Boolean(string='已导出', compute='_compute_exported', store=True)

    _sql_constraints = [
        ('dataset_name_unique', 'unique(name)', '训练样本编号必须唯一。'),
    ]

    @api.model
    def create(self, vals):
        if vals.get('name', '新建') == '新建':
            vals['name'] = self.env['ir.sequence'].next_by_code('agri.dataset.entry') or '新建'
        return super().create(vals)

    @api.depends('export_batch', 'exported_at')
    def _compute_exported(self):
        for record in self:
            record.exported = bool(record.export_batch and record.exported_at)

    def action_mark_exported(self, batch_name=False):
        if not batch_name:
            batch_name = self.env['ir.sequence'].next_by_code('agri.dataset.export.batch') or fields.Date.today().isoformat()
        self.write({
            'export_batch': batch_name,
            'exported_at': fields.Datetime.now(),
        })
        return batch_name

    def action_reset_exported(self):
        self.write({
            'export_batch': False,
            'exported_at': False,
        })
        return True

